<?php

namespace app\admin\controller;

use think\facade\{View, Session, Db};
use app\BaseController;

class Admin extends Base
{

    public function auser()
    {
        if($this->Ajax){
            $page=input("page",1);
            $size = input("limit", 10);
            $mp=[];
            if(trim(input('username'))){
                $mp[]=["username", "like","%".trim(input('username'))."%"];
            }
            if (trim(input('reaname'))) {
                $mp[] = ["reaname", "like", "%" . trim(input('reaname')) . "%"];
            }
            if (trim(input('mobile'))) {
                $mp[] = ["mobile", "like", "%" . trim(input('mobile')) . "%"];
            }


            $lst=Db::name("auser")->where($mp)->order("id asc")->page($page,$size)->select()->toArray();
            foreach($lst as &$v){
                $rolemsg=Db::name("role_user")->find($v['role_id']);
   
                $v['rolename']=$rolemsg['name'];
                $v['addtime']=date("Y-m-d H:i:s",$v['addtime']);
            }
            $count= Db::name("auser")->where($mp)->count();

           

            return resmsg(0,"检索成功",$lst, $count);
        }
        return View::fetch();
    }
    // 开启或冻结用户
    public function setUserStatus(){
        $is=Db::name("auser")->where("id",input("id"))->update(['status'=>input('status')]);
        return $is ? returnmsg(200,"操作成功") : returnmsg(199, "操作异常"); 
    }
    // 开启 - 冻结权限
    public function setMenuStatus(){
        $is=Db::name("limit_operate")->where("id",input("id"))->update(['status'=>input('status')]);
        return $is ? returnmsg(200,"操作成功") : returnmsg(199, "操作异常"); 
    }
    // 添加-修改用户信息
    public function auseredit(){
        $id=input('id');
        if(input('t')){
            $id=Session("lt_auser")['id'];
        }
        $msg=Db::name("auser")->find($id);
        View::assign("msg",$msg);
        $data=Db::name("role_user")->order("id asc")->select()->toArray();
        View::assign("lst",$data);
        return View::fetch("admin/src/auseredit");
    }
    // 提交用户信息-保存或添加
    public function auserSave(){
        $param = input('param.', []);

        $param['id'] = input('param.tn') ? Session('lt_auser')['id'] : $param['id'];

        $file = [];
        if (request()->file()) {
            $file = request()->file('img');
        }

        $mp = [];
        $mp[] = $param['id'] ? ["id", "<>", $param['id']] : ["id", ">", 0];
        $is = Db::name("auser")->where($mp)->where("username", $param['username'])->value("id");

        if ($is) {
            return returnmsg(201, "用户名不能重复");
        }
        $is = Db::name("auser")->where($mp)->where("mobile", $param['mobile'])->value("id");
        if ($is) {
            return returnmsg(201, "手机号不能重复");
        }
        if(!input('role_id') && !input('t')){
            return returnmsg(201, "请选择角色");
        }
        if ($file) {
            $img = uniqid() . ".jpg";
            \think\facade\Filesystem::disk('efile')->putFileAs('auserimg', $file, $img);
            $param['img'] = $img;
        }
        $param['mid'] = Session("lt_auser")["id"];
        $param['edittime'] = time();
        if (!$param['id']) {
            unset($param['id']);
            $param['addtime'] = time();
            $param['password'] = md5($param['password']);
            $param['img'] = $param['img'] ?? _user_header_img_data;
        } else {
            $param['password'] = $param['password'] == Db::name("auser")->where("id", $param['id'])->value("password") ? $param['password'] : md5($param['password']);

            $param['status'] = $param['id'] == 1 ? 0 : $param['status'];
        }

        // if ($param['id'] != 1 && !$param['role_id'] && !input('param.tn')) {
        //     return returnmsg(201, "请选择角色");
        // }
        $is = Db::name("auser")->strict(false)->save($param);
        if (input('param.tn')) {
            //修改个人信息后 更新缓存信息
           // Session::set("st_auser", Db::name("auser")->find(Session("st_auser")['id']));
        }

        return $is ? returnmsg(200, "操作成功") : returnmsg(201, "操作失败");
    }
    // 删除用户信息
    public function auserDelete(){
        if(input('id')==1){
            return returnmsg(199,"该用户不可删除");
        }

        $is=Db::name("auser")->delete(input('id'));
        return returnmsg(200,"操作成功");

    }
    // 权限设置-列表
    public function operateset(){
        if($this->Ajax){
            $data=Db::name("limit_operate")->order("xh asc")->select()->toArray();
            return resmsg(0,"加载成功",$data);
        }

        return View::fetch();
    }
    //角色列表
    public function rolelst(){
          if($this->Ajax){
            $data=Db::name("role_user")->order("id asc")->select()->toArray();
            foreach ($data as &$v){
                $v['addtime']=date("Y-m-d H:i:s",$v['addtime']);
                $v['count']=Db::name("auser")->where("role_id",$v['id'])->count();
            }
            return resmsg(0,"加载成功",$data);
        }

        return View::fetch();
    }
    
    
    // 权限设置 - 单个权限 增加-更新
    public function operateitem(){
        $pmsg=Db::name("limit_operate")->find(input('pid'));
        $data = array_values(array_filter(array_reverse($this->getparentre($pmsg,[ $pmsg ]))));
        $ptitle= "根分类";
        if($pmsg){
            foreach($data as $v){
                $ptitle.="->".$v['title'];
            }
        }
        $msg=Db::name("limit_operate")->find(input('id'));
        $msg['ptitle']=$ptitle;
        View::assign("msg",$msg);
 
        return View::fetch('admin/src/operateitem');
    }
    //递归无限父类数组
    private function getparentre($da, $data = [])
    {
        $da = Db::name("limit_operate")->find($da['pid']);
        $data[] = $da;
        if (!empty($da['pid'])) {
            return $this->getparentre($da, $data);
        }
        return $data;
    }
    // 权限编辑
    public function opItemSave(){
        $param = input("param.");
        $data = [];
       
        $data['openType'] = input("openType");
        $data['type'] = $param["type"];
        $data['title'] = trim($param["title"]);
        if (empty($data['title'])) {
            return returnmsg(199, "字段名称不能为空！");
        }
        
        $data['url'] = trim(input('url'));
        $data['icon'] = trim(input('icon'));
        $data['status'] = trim($param['status']);
      
        $mp = [];
        $mp['id'] = ["neq", $param["id"]];
        $mp['title'] = $param["title"];


        // $delfv=0;
        if (!$param['id']) {
             $data['pid'] =input('pid',0);
             $data['xh']=Db::name("limit_operate")->where("pid",$data['pid'])->count();
            $param['id'] = Db::name("limit_operate")->insertGetId($data);
        } else {
            $is = Db::name("limit_operate")->where("id", $param['id'])->find();
            Db::name("limit_operate")->where("id", $param['id'])->update($data);
        }



        return returnmsg(200, "权限更新成功");
    }
    //获取权限列表
    public function getOperNp(){
       $data= $this->getchliddata(0);
        return resmsg(0,"加载成功",$data);
    }
    

    //获取子类
    private function getchliddata($id)
    {
        $data = Db::name("limit_operate")->where("pid", $id)->select()->toArray();

        foreach ($data as $k => $v) {
           
            $data[$k]["children"] = $this->getchliddata($v['id']);
            if($data[$k]["children"]){
                unset($data[$k]["children"]);
            }
        }

        return $data;
    }
    //删除权限
    public function operateDel(){
        
       Db::name("limit_operate")->where("id",input('id'))->delete();
       Db::name("limit_operate")->where("pid",input('id'))->delete();
    
       return returnmsg(200,"操作成功");
        
    }
    public function operatelst(){
        $lst= Db::name("limit_operate")->where("pid",input('pid'))->order("xh asc")->select()->toArray();
        
        View::assign('lst',$lst);
        return View::fetch("admin/src/operatelst");
    }
    public function opItemxhSave(){
        $idarr=array_filter( explode(",",input('ids')) );
        if($idarr){
            $arr=[];
            foreach ($idarr as $k => $v){
                $arr[]=[
                    'id'=>$v,
                    'xh'=>$k
                    ];
            }
            

            $el=new \app\admin\model\LimitOperate();
            $res=$el->saveAll($arr);
        }
      
       return returnmsg(200,"数据更新成功");
        
    }
    public function roleedit(){
        
            $lse=Db::name("limit_operate")->where("pid",0)->order("xh asc")->select()->toArray();
            foreach($lse as &$v){
                $v['limits']=Db::name("limit_operate")->where("pid",$v['id'])->order("xh asc")->select()->toArray();
            }   
            View::assign("lse",$lse);
            $msg=Db::name("role_user")->find(input('id',0));
            $limits=[];
            if($msg){
                $limits=json_decode($msg['limits'],true);
            }
            View::assign('limits',$limits);
            View::assign('msg',$msg);
        return View::fetch("admin/src/roleedit");
    }
    // 提交角色编辑
    public function roleSave(){
        
        $param=input("param.");
        if(!trim($param['name'])){
            returnmsg(201, "角色名称不能为空");   
        }
        $mp = [];
        $mp[] = $param['id']!=0 ? ["id", "<>", $param['id']] : ["id", ">", 0];
        $is=Db::name("role_user")->where($mp)->find();
        if($is){
            returnmsg(201, "角色名称不能重复");
        }

        if($param['id']==0){
            $param['addtime']=time();
            unset($param['id']);
        }
        $param['limits']=json_encode($param['operate_id']);
        $is = Db::name("role_user")->strict(false)->save($param);

        return $is ? returnmsg(200, "操作成功") : returnmsg(201, "操作失败");

    }
    // 删除权限
    public function roleDelete(){
        $is=Db::name("auser")->where("role_id",input("id"))->count();
        if($is){
           return returnmsg(201, "不可删除，请先解绑用户");
        }
        Db::name("role_user")->delete(input('id'));
        return returnmsg(200, "操作成功");
    }  
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    


}
